import socket
import threading

# 存储序列号及其使用人数
licenses = {
    "ABCDEFGHIJ": {"max_users": 10, "current_users": 0}
}

def handle_client(client_socket):
    try:
        while True:
            request = client_socket.recv(1024).decode('utf-8')
            if not request:
                break
            print(f"Received: {request}")
            parts = request.split(':')
            if parts[0] == "LICENSE_REQUEST":
                username = parts[1]
                password = parts[2]
                license_type = parts[3]
                if license_type in licenses and licenses[license_type]["current_users"] < licenses[license_type]["max_users"]:
                    licenses[license_type]["current_users"] += 1
                    response = f"LICENSE_RESPONSE:ACCEPTED:Welcome {username}"
                else:
                    response = "LICENSE_RESPONSE:DENIED:License limit reached or invalid license type"
                client_socket.send(response.encode('utf-8'))
    finally:
        client_socket.close()

def main():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(("0.0.0.0", 9999))
    server.listen(5)
    print("Server listening on port 9999")
    
    while True:
        client_socket, addr = server.accept()
        print(f"Accepted connection from {addr}")
        client_handler = threading.Thread(target=handle_client, args=(client_socket,))
        client_handler.start()

if __name__ == "__main__":
    main()
